package com.ruoyi.common.utils.file;

import com.ruoyi.common.utils.ExceptionUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 上传文件到腾讯云cos存储 demo
 *
 * @author qiqi
 * @date 2021-9-9
 */
public class UploadFileToCosUtils {

	private UploadFileToCosUtils() {
		throw new IllegalStateException("Utility class");
	}

	private static Logger log = LoggerFactory.getLogger(UploadFileToCosUtils.class);

	/**
	 * 上传文件
	 * 
	 * @param reqUrl   url
	 * @param filePath 文件路径
	 */
	public static String uploadFile(String reqUrl, String filePath) {
		String imageUrl = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost(reqUrl);

			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000)
					.build();
			httppost.setConfig(requestConfig);

			File file = new File(filePath);

			String fileName = file.getName();
			fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
			ByteArrayBody fileArrayBody = new ByteArrayBody(getBytes(file), fileName);

			HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fileArrayBody).build();

			httppost.setEntity(reqEntity);

			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					imageUrl = EntityUtils.toString(response.getEntity());

					log.info("image url : {} ", imageUrl);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
			return imageUrl;
		} catch (IOException e) {
			log.info("图片服务器异常:{}", ExceptionUtil.getExceptionMessage(e));
			return imageUrl;
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				log.info("图片服务器异常:{}", ExceptionUtil.getExceptionMessage(e));
			}
		}

	}

	/**
	 * 转化bytes
	 * <p>
	 * Title: getBytes
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param file
	 * @return
	 */
	public static byte[] getBytes(File file) {
		byte[] buffer = null;
		try (FileInputStream fis = new FileInputStream(file)) {

			ByteArrayOutputStream bos = new ByteArrayOutputStream(8192);
			byte[] b = new byte[8192];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			bos.close();
			buffer = bos.toByteArray();
		} catch (IOException e) {
			log.info("图片服务器异常:{}", ExceptionUtil.getExceptionMessage(e));
		}
		return buffer;

	}
}
